package cn.enilu.flash.api.controller.order;

import cn.enilu.flash.api.controller.BaseController;
import cn.enilu.flash.bean.entity.order.PayOrder;
import cn.enilu.flash.bean.entity.order.TaskOrder;
import cn.enilu.flash.bean.entity.task.HelpTask;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.security.JwtUtil;
import cn.enilu.flash.service.order.PayOrderService;
import cn.enilu.flash.service.order.TaskOrderService;

import cn.enilu.flash.bean.core.BussinessLog;
import cn.enilu.flash.bean.constant.factory.PageFactory;
import cn.enilu.flash.bean.enumeration.BizExceptionEnum;
import cn.enilu.flash.bean.exception.ApplicationException;
import cn.enilu.flash.bean.vo.front.Ret;
import cn.enilu.flash.bean.vo.front.Rets;

import cn.enilu.flash.service.task.HelpTaskService;
import cn.enilu.flash.service.task.MoneyInfoService;
import cn.enilu.flash.utils.StringUtil;
import cn.enilu.flash.utils.factory.Page;


import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;


@RestController
@RequestMapping("/task/order")
public class TaskOrderController extends BaseController {
	private  Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private MoneyInfoService moneyInfoService;
	@Autowired
	private TaskOrderService taskOrderService;
	@Autowired
	private HelpTaskService helpTaskService;
	@Autowired
	private PayOrderService payOrderService;

	@GetMapping(value = "/list")
	@RequiresPermissions(value = "taskOrder")
	public Ret list(@RequestParam(required = false) Long id,
					@RequestParam(required = false) Integer state) {
		Page<TaskOrder> page = new PageFactory<TaskOrder>().defaultPage();
		page.addFilter("appeal", SearchFilter.Operator.ISNOTNULL,SearchFilter.Operator.ISNOTNULL);
		if(state != null && state != 0){
			page.addFilter("state",state);
		}
		page = taskOrderService.queryPage(page);
		return Rets.success(page);
	}

	/**
	 *
	 * @param appealResult 申述处理类型： 1申述成功，2申述失败
	 * @param failureRecovery
	 * @return
	 */
	@PutMapping("submitAppeal")
	public Ret submitAppeal(Long orderId, Integer appealResult, String failureRecovery){
		TaskOrder taskOrder = taskOrderService.get(orderId);
		HelpTask helpTask = helpTaskService.get(taskOrder.getTaskId());
		if(StringUtil.isNullOrEmpty(failureRecovery)) return Rets.failure("处理回复内容不能为空~");
		if(appealResult == 1){
			taskOrder.setState(3);// 已完成
			taskOrder.setResult(3);//审核结果： 申述通过
		}else if(appealResult == 2){
			taskOrder.setState(6);// 取消订单
			taskOrder.setResult(2);//审核结果： 不通过
			helpTask.setLastNum(helpTask.getLastNum()+1);
			if(helpTask.getLastNum() == 1 && helpTask.getState() == 6){
				helpTask.setState(1);
			}
			helpTaskService.update(helpTask);// 返还份数
		}else {
			return Rets.failure("未选择申述结果");
		}
		taskOrder.setFailureRecovery(failureRecovery);
		taskOrder.setSysUserId(JwtUtil.getUserId());
		TaskOrder update = taskOrderService.update(taskOrder);
		if(update != null){
			if(update.getState() == 3) {
				moneyInfoService.setMoneyInfo(taskOrder.getTaskId(),taskOrder.getCreateBy(),1,taskOrder.getMoney());// 加钱
			}
			return Rets.success();
		}else {
			return Rets.failure("处理失败！");
		}


	}
	@GetMapping("getServiceFeeIncome")
	public Ret getServiceFeeIncome(){
		List<String> serviceFeeIncomes = new LinkedList<>();
		List<SearchFilter> list = new ArrayList<>();
		list.add(new SearchFilter("state", SearchFilter.Operator.EQ, 3));
		for(int i = 7;i>0;i--){
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE,-i);//减7天
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			Calendar tepCal = (Calendar)cal.clone();
			tepCal.add(Calendar.DATE,1);
			list.add(new SearchFilter("createTime", SearchFilter.Operator.GTE,cal.getTime()));
			list.add(new SearchFilter("createTime", SearchFilter.Operator.LTE,tepCal.getTime()));

			List<TaskOrder> taskOrders = taskOrderService.queryAll(list);
			BigDecimal count = BigDecimal.ZERO;
			for(TaskOrder taskOrder:taskOrders){
				HelpTask helpTask = helpTaskService.get(taskOrder.getTaskId());
				count = count.add(helpTask.getServiceFee());
			}
			serviceFeeIncomes.add(count.toString());
			list.remove(1);
			list.remove(1);
		}
		return Rets.success(serviceFeeIncomes);
	}
	@GetMapping("getIncome")
	public Ret getIncome(){
		List<PayOrder> brokerage = payOrderService.queryAll(new SearchFilter("brokerage", SearchFilter.Operator.LTE, 0));
		BigDecimal vipIncome = BigDecimal.ZERO;
		BigDecimal serviceFeeIncome = BigDecimal.ZERO;
		for (PayOrder payOrder:brokerage){
			vipIncome = vipIncome.add(payOrder.getTotalServiceFee());
		}
		List<TaskOrder> taskOrderList = taskOrderService.queryAll(new SearchFilter("state", SearchFilter.Operator.EQ, 3));
		for(TaskOrder taskOrder:taskOrderList){
			HelpTask helpTask = helpTaskService.get(taskOrder.getTaskId());
			serviceFeeIncome = serviceFeeIncome.add(helpTask.getServiceFee());
		}
		Map<String,Object> map = new HashMap<>();
		map.put("vipIncome",vipIncome);
		map.put("serviceFeeIncome",serviceFeeIncome);
		map.put("totalIncome",vipIncome.add(serviceFeeIncome));
		return Rets.success(map);
	}
	@PostMapping
	@BussinessLog(value = "新增接单订单类", key = "name")
	@RequiresPermissions(value = "taskOrderAdd")
	public Ret add(@ModelAttribute TaskOrder taskOrder){
		taskOrderService.insert(taskOrder);
		return Rets.success();
	}
	@PutMapping
	@BussinessLog(value = "更新接单订单类", key = "name")
	@RequiresPermissions(value = "taskOrderUpdate")
	public Ret update(@ModelAttribute TaskOrder taskOrder){
		taskOrderService.update(taskOrder);
		return Rets.success();
	}
	@DeleteMapping
	@BussinessLog(value = "删除接单订单类", key = "id")
	@RequiresPermissions(value = "taskOrderDelete")
	public Ret remove(Long id){
		if (id == null) {
			throw new ApplicationException(BizExceptionEnum.REQUEST_NULL);
		}
		taskOrderService.delete(id);
		return Rets.success();
	}
}